package com.google.jessewilson.codesearch.intellij.configuration;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.jessewilson.codesearch.configuration.Configuration;
import com.google.jessewilson.codesearch.configuration.ConfigurationManager;
import com.google.jessewilson.codesearch.intellij.CodeSearchInjector;
import com.google.jessewilson.codesearch.io.jdom.Externalizer;
import com.google.jessewilson.codesearch.ui.Clipboard;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;

import javax.swing.*;

/**
 * A place where we can hang global configuration data from,
 * such as which code search servers we're using.
 *
 * @author jessewilson
 */
public class ConfigurationUi
    implements com.intellij.openapi.components.ApplicationComponent,
    Configurable, JDOMExternalizable {

  @Inject private ConfigurationManager configurationManager;
  @Inject private Clipboard clipboard;
  @Inject private Provider<ConfigurationPanel> configurationPanelProvider;

  private final Externalizer<Configuration> externalizer
      = new Configuration.MyExternalizer();

  /** the configuration panel does the actual editing */
  private ConfigurationPanel configurationPanel;

  public ConfigurationUi() {
    CodeSearchInjector.inject(this);
  }

  public String getComponentName() {
    return "CodeSearch";
  }

  public String getDisplayName() {
    return "CodeSearch";
  }

  public Icon getIcon() {
    return null;
  }

  public String getHelpTopic() {
    return null;
  }

  // Methods for implementing Configurable
  public JComponent createComponent() {
    if (configurationPanel == null) {
      configurationPanel = configurationPanelProvider.get();
      configurationPanel.setValue(configurationManager.getCurrent());
    }

    return configurationPanel.getComponent();
  }
  public boolean isModified() {
    return configurationPanel.isModified();
  }
  public void apply() throws ConfigurationException {
    configurationManager.setCurrent(configurationPanel.getValue());
  }
  public void reset() {
    configurationPanel.setValue(configurationManager.getCurrent());
  }
  public void disposeUIResources() {
    configurationPanel = null;
  }

  // Methods for implementing JDOMExternalizable....
  public void writeExternal(Element element) throws WriteExternalException {
    externalizer.writeExternal(element,
        configurationManager.getCurrent());
  }

  public void readExternal(Element element) throws InvalidDataException {
    configurationManager.setCurrent(
        externalizer.readExternal(element));
  }

  // Methods for implementing ApplicationComponent
  public void initComponent() { }
  public void disposeComponent() { }
}